import { login } from '@/api/admin/administrator'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { restRourers } from '@/router'
import store from '../index'
import router from '../../router'

const state = {
    token: getToken()
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token
    }
}

const actions = {
    // user login
    login({ commit }, userInfo) {
        return new Promise((resolve, reject) => {
            login(userInfo).then(response => {
                setToken(response.data)
                commit('SET_TOKEN', response.data)
                store.dispatch('permission/getSelfMenus').then(() => {
                    const hasRouters = store.getters.routers
                    if (hasRouters) {
                        router.addRoutes(store.getters.routers)
                    }
                })
                store.dispatch('permission/getAllButtomMenus')
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },
    // 退出登陆
    outLogin({ commit }) {
        return new Promise((resolve) => {
            commit('SET_TOKEN', null)
            removeToken()
            restRourers()
            resolve()
        })
    },


}

export default {
    namespaced: true,
    actions,
    state,
    mutations
}